#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

/* int Total = 0; */

class Computer
{
public:
    Computer(const char * brand,double price)
    : _brand(new char[strlen(brand) + 1]())
    , _price(price)
    {
        _totalPrice += _price;
        cout << "Computer(const char *,double)" << endl;
        strcpy(_brand,brand);
    }

    ~Computer(){
        cout << "~Computer()" << endl;
        if(_brand){
            _totalPrice -= _price;
            delete [] _brand;
            _brand = nullptr;//安全回收
        }
    }

    Computer(const Computer & rhs)
    : _brand(new char[strlen(rhs._brand) + 1]())
    , _price(rhs._price)
    {
        _totalPrice += _price;
        cout << "Computer(const Computer &)" << endl;
        strcpy(_brand,rhs._brand);
    }

    Computer & operator=(const Computer & rhs){
        cout << "赋值运算符函数" << endl;
        if(this != &rhs){//1.自赋值情况的判断
            _totalPrice -= _price;
            delete [] _brand; //2.回收左操作数的数据成员原本管理的堆空间
            _brand = new char[strlen(rhs._brand) + 1]();//3.深拷贝
            strcpy(_brand,rhs._brand);
            _price = rhs._price;//以及其他的数据成员完成简单赋值
            _totalPrice += _price;
        }
        return *this;//4.返回本对象
    }

    //const Computer * const this
    void print() const{
        /* this = new Computer("ABC",1000); */
        //通过_brand找到该地址存储的内容，进行修改，没有被限定
        _brand[0] = 'X';
        //const成员函数的限定是限定在函数中不能修改对象的数据成员
        //对于指针数据成员，也就是不能修改地址值（修改指向）
        /* _brand = new char[10](); */
        /* _price  = 1; */
        cout << "brand:" << _brand << endl;
        cout << "price:" << _price << endl;
    }

    static void printTotalPrice(){
        cout << "totalPrice:" << _totalPrice << endl;
        //静态的成员函数中没有this指针，不能直接访问非静态的成员
        /* cout << "price:" << _price << endl; */
    }
private:
    char * _brand;
    double _price;
    static double _totalPrice;
};
double Computer::_totalPrice = 0;


void test0(){
    Computer::printTotalPrice();
    cout << sizeof(Computer) << endl;
    Computer pc("Apple",20000);
    Computer pc2("Huawei",21000);
    Computer pc3("Acer",8000);
    pc3.print();

    /* pc.printTotalPrice(); */
    Computer::printTotalPrice();


    /* pc3.print(); */
    /* cout << endl; */
    /* pc2.print(); */
    /* cout << endl; */
    /* pc.print(); */

    /* cout << endl; */
    /* Computer pc4 = pc; */
    /* pc4.print(); */

    /* cout << endl; */
    /* pc2 = pc; */
    /* pc2.print(); */

    /* cout << pc._totalPrice << endl; */
    /* cout << pc2._totalPrice << endl; */
    /* cout << Computer::_totalPrice << endl;//这种访问方式更常用 */

    
}

int main(void){
    test0();
    return 0;
}
